#!/bin/bash

set -e

# This script runs the NRP repository tools

# Environment variables
# PYTHON:
#              python executable to use for running the NRP tools
# LOCAL_NRP_DEVTOOLS_LOCATION:
#              location of the local NRP repository.
#              If set, do not clone the NRP repository but use the local one.


# If there is a local environment file, source it. This is necessary on Mac OS X
# to set the correct environment variables for the python executable.
# An example file on mac os x is:
#
# ❯ cat ~/.envrc.local
#
# # dynamic libraries (such as cairo)
# export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib
#
if [ -f ~/.envrc.local ] ; then
  source ~/.envrc.local
fi


SUPPORTED_PYTHON_VERSIONS=(3.10)

if [ -z "$PYTHON" ] ; then

  # find a supported python
  for version in "${SUPPORTED_PYTHON_VERSIONS[@]}"; do
      if command -v python$version >/dev/null 2>&1; then
          PYTHON=python$version
          break
      fi
  done

  if [ -z "$PYTHON" ] ; then
    echo "No supported python version found. Please install python 3.9 or higher
    or set the PYTHON environment variable to the python executable."
    exit 1
  fi
fi

venv_directory=$(dirname "$0")/.venv

if [ ! -d "$venv_directory" ] ; then
  mkdir "$venv_directory"
fi

devtools_cli_directory=$(dirname "$0")/.nrp/devtools

# if there is a devtools directory and can not call nrp-devtools inside it,
# remove the directory
if [ -d "$devtools_cli_directory" ] ; then
  if ! "$devtools_cli_directory"/bin/nrp-devtools --help >/dev/null 2>&1 ; then
    rm -rf "$devtools_cli_directory"
  fi
fi

if [ ! -d "$devtools_cli_directory" ] ; then
  # make parent directory if it does not exist
  if [ ! -d "$(dirname "$devtools_cli_directory")" ] ; then
    mkdir -p "$(dirname "$devtools_cli_directory")"
  fi
  $PYTHON -m venv "${devtools_cli_directory}"
  "${devtools_cli_directory}"/bin/pip install -U setuptools pip wheel
  if [ -z "$LOCAL_NRP_DEVTOOLS_LOCATION" ] ; then
    "${devtools_cli_directory}"/bin/pip install nrp-devtools
  else
    "${devtools_cli_directory}"/bin/pip install -e "$LOCAL_NRP_DEVTOOLS_LOCATION"
  fi
fi

source "$devtools_cli_directory"/bin/activate

"$devtools_cli_directory"/bin/nrp-devtools "$@"
